package gunglad.com.utils

import org.apache.commons.pool2.impl.GenericObjectPoolConfig
import redis.clients.jedis.JedisPool

/**
 * @author chenjie
 * @date 2020/12/10 15:01
 */
object RedisUtil {
  private val redisHost: String = "localhost"
  private val redisPort: Int = 6379
  private val redisTimeOut: Int = 30000 // ms
  private val maxTotal = 300
  private val maxIdle = 100
  private val minIdle = 1

  @transient private var pool: JedisPool = _
  makePool(redisHost,redisPort, redisTimeOut, maxTotal, maxIdle, minIdle)

  def makePool(redisHost: String, redisPort: Int, redisTimeout: Int,
               maxTotal: Int, maxIdle: Int, minIdle: Int): Unit = {
    makePool(redisHost, redisPort, redisTimeout, maxTotal, maxIdle, minIdle, true, false, 10000)
  }

  def getOrDefalut(): Unit ={

  }
  def makePool(redisHost: String, redisPort: Int, redisTimeout: Int,
               maxTotal: Int, maxIdle: Int, minIdle: Int, testOnBorrow: Boolean,
               testOnReturn: Boolean, maxWaitMillis: Long): Unit = {
    if (pool == null) {
      val poolConfig = new GenericObjectPoolConfig()
      poolConfig.setMaxTotal(maxTotal)
      poolConfig.setMaxIdle(maxIdle)
      poolConfig.setMinIdle(minIdle)
      poolConfig.setTestOnBorrow(testOnBorrow)
      poolConfig.setTestOnReturn(testOnReturn)
      poolConfig.setMaxWaitMillis(maxWaitMillis)
//      val path = "/home/app/private-conf/db.json"
//      D:\proj\private-conf\redis.json
//val path = "D:\\proj\\private-conf\\redis.json"
val path = "/home/app/private-conf/redis.json"
      val map = JsonUtil.jsonFileToMap(path)
//      map("")

      var password = ""
      if (map.contains("password")) {
        password = map("password")
      }
//      解决jedis密码为空问题_L13763338360的博客-CSDN博客_jedispool 无密码
//        https://blog.csdn.net/L13763338360/article/details/108761150
//      pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout,"123456")
//      pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout,password)
//      JedisPool 如果密码是空的 要写吗
      if(null==password||password==""){
        pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout,null)
      }else{
        pool = new JedisPool(poolConfig, redisHost, redisPort, redisTimeout,password)
      }

//      JedisPool 密码 空 怎么写

      val hook = new Thread {
        override def run: Unit = pool.destroy()
      }
      sys.addShutdownHook(hook.run)
    }
  }

  def getPool: JedisPool = {
    assert(pool != null)
    pool
  }
}
